#include "derivative.h" /* include peripheral declarations */
#include "CPU\Clock.h"
#include "CPU\arm_cm4.h"
#include "CPU\FlexTimer.h"
//The keyword volatile tells the compiler the the variable
//can change in a "background" operation that compiler is not aware of.
//This forces the compiler to make no assumptions about what its value may be and
//to always read its value before an operation.
//volatile unsigned short FlexTimerTick = 0;


void InitFlexTimer0()
{
	SIM_SCGC6 |= SIM_SCGC6_FTM0_MASK; //Enable the clock to the FTM0 module
	
	//turn off FTM write protection;
	FTM0_MODE |= FTM_MODE_WPDIS_MASK;
	
	FTM0_SC = 0; //Make sure its Off!
	//Edit registers when no clock is fed to timer so the MOD value, gets pushed in immediately

	FTM0_SC |= FTM_SC_PS(FTM0_CLK_PRESCALE); //divide the input clock down by 2^FTM0_CLK_PRESCALE
	FTM0_CNT = 0;	//reset the counter to zero
	FTM0_MOD = (CORE_CLOCK/(1<<FTM0_CLK_PRESCALE))/FTM0_OVERFLOW_FREQUENCY ;  //Set the overflow rate
	FTM0_SC |= FTM_SC_TOIE_MASK; //Enable the interrupt mask.
	FTM0_SC |= FTM_SC_CLKS(1); //Select the System Clock
	
	
	//The enable irq function gives us a nice way to enable interrupts on the NVIC.  It modifies 
	//the core ARM registers for us.  All we need to know is the interrupt number.
	//
	//The reference manual for the Kinetis K40 lists the interrupt numbers. See Table 3-4 (page 73)
	// of K40P144M100SF2RM for the interrupt channel assignments.
	//
	//IMPORTANT!   The first 16 interrupts are part of the ARM cortex M4 core.  THEY DO NOT PASS THROUGH THE NVIC.
	//You only enable IRQs on the NVIC for the vectors above #15.   FOr example the Systick module is part of the
	//arm core.   See the Systick.C for an example.
	//
	//The enable_irq() function assume you are giving a peripheral irq number.   This means you need to subtract 16
	//from the vector number in table 3-4.   The MK40X256VMD100.h header file has an enumeration of the vector numbers 
	//for the K40 Variant.  
	//
	//Make sure that the interrupt vector table (in Kinetis_sysinit.c)  has an entry for your interrupt vector function.
	//See kinetis_sysinit.c file.  The kinetis_sysinit.c puts a vector table(pointers to the interrupt vectors) in FLASH.
	//It is possible to relocate the table into RAM if you want....   (the SCB_VTOR register).  This is useful if you want
	//to do something crazy like change the interrupt functions on the fly.   For most applications,  the table can be static
	//and defined in flash.
	
	//The INT_FTM0 definition is in the MK40X256VMD100.h file.  remember, the enable_irq() function expects the NVIC irq number, 
	//not the vector number!!@
	enable_irq(INT_FTM0-16);
}
